local mymqtt = require "mymqtt"
local myjson = require "myjson"
local mywifi = require "mywifi"
local myio = require "myio"
--local myusart = require "myusart"

--myusart.usartInit()
myjson.readJsonFromfile()       --读取SSID,PWD,mqtt IP
mywifi.wifiInit(myjson.ssid, myjson.pwd)
myio.ioInit()


local t = tmr.create()
function MqttConnect()
    if (wifi.sta.status() == wifi.STA_GOTIP) then
        print(wifi.sta.getip())
        t:unregister()
        t=nil
        mymqtt.mqttInit(myjson.mqttIP, 'SW_ID')
    end
end

t:alarm(500, tmr.ALARM_AUTO, MqttConnect)

--print(wifi.sta.clearconfig())     //清理wifi存储信息

-- on publish message receive event
mymqtt.m:on("message", function(client, topic, data)
    print(topic .. ":" .. data)
    if data ~= nil then   
        if (data == 'ON') then
            myio.On()
            client:publish("/topic", node.chipid() .. " ON", 0, 0)
        elseif (data == 'OFF') then
            myio.Off()
            client:publish("/topic", node.chipid() .. " OFF", 0, 0)
        elseif string.find(data, 'ioRoll') ~= nil then
            local len = string.len(data)
            local tem = string.sub(data,7,len)
            myio.ioRoll(tem)
            client:publish("/topic", node.chipid() .. " ioRoll", 0, 0)
        elseif (data == 'STOP') then
            myio.STOP()
            client:publish("/topic", node.chipid() .. " STOP", 0, 0)
        end
    end
end)
